<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>某某系统登录/注册</title>
    <style>
        :root {
            --primary-color: #4a90e2;
            --error-color: #e74c3c;
            --success-color: #2ecc71;
            --text-color: #333;
            --bg-color: #ffffff;
            --border-color: #e0e0e0;
            --shadow-color: rgba(0,0,0,0.1);
            --transition-speed: 0.3s;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: 'Segoe UI', Arial, sans-serif;
        }

        body {
            background-color: var(--bg-color);
            color: var(--text-color);
        }

        .container {
            width: 100vw;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            position: relative;
            overflow: hidden;
        }

        .auth-form {
            width: 100%;
            max-width: 400px;
            background: var(--bg-color);
            padding: 2.5rem;
            border-radius: 12px;
            box-shadow: 0 8px 24px var(--shadow-color);
            position: relative;
            z-index: 1;
            transition: transform 0.3s ease;
        }

        .form-title {
            text-align: center;
            color: var(--text-color);
            margin-bottom: 2rem;
            font-size: 1.8rem;
            position: relative;
        }

        .form-title::after {
            content: "";
            position: absolute;
            width: 60%;
            height: 4px;
            background: var(--primary-color);
            bottom: -20px;
            left: 20%;
            border-radius: 2px;
        }

        .input-group {
            margin-bottom: 1.8rem;
            position: relative;
        }

        input {
            width: 100%;
            padding: 14px 45px 14px 15px;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            background: rgba(248, 249, 250, 0.5);
            color: var(--text-color);
            font-size: 16px;
            transition: all var(--transition-speed) ease;
        }

        input:focus {
            outline: none;
            border-color: var(--primary-color);
            background: white;
            box-shadow: 0 2px 8px rgba(74,144,226,0.1);
        }

        button {
            width: 100%;
            padding: 14px;
            margin-top: 12px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            transition: all var(--transition-speed) ease;
            text-transform: uppercase;
            letter-spacing: 1px;
            border: none;
            font-weight: 600;
            position: relative;
            overflow: hidden;
        }

        #denglu {
            background: var(--primary-color);
            color: white;
        }

        #denglu:hover {
            background: color-mix(in srgb, var(--primary-color) 70%, #357ab8);
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(74,144,226,0.2);
        }

        #zhuce {
            background: white;
            color: var(--primary-color);
            border: 1px solid var(--border-color);
            margin-top: 10px;
        }

        #zhuce:hover {
            background: rgba(74,144,226,0.05);
        }

        .toggle-text {
            text-align: center;
            margin: 1.5rem 0;
            color: #666;
            font-size: 14px;
        }

        .error-message {
            color: var(--error-color);
            margin-top: 0.8rem;
            text-align: center;
            min-height: 1.2em;
            display: none;
            font-size: 14px;
            animation: fadeIn 0.3s ease;
        }

        .success-message {
            color: var(--success-color);
            text-align: center;
            font-size: 16px;
            padding: 1rem;
            display: none;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        @media (max-width: 768px) {
            .form-title {
                font-size: 1.5rem;
            }
            
            input {
                padding: 12px 40px 12px 15px;
            }
        }
    </style>
</head>
<body>
    <div class="container">
        <form class="auth-form" id="authForm">
            <h1 class="form-title" id="formTitle">账号登录</h1>
            
            <!-- 登录表单 -->
            <div id="loginFields">
                <div class="input-group">
                    <input type="text" id="username" placeholder="用户名" required>
                    <div class="error-message" id="usernameError"></div>
                </div>
                <div class="input-group">
                    <input type="password" id="password" placeholder="密码" required>
                    <div class="error-message" id="passwordError"></div>
                </div>
            </div>

            <!-- 注册表单 -->
            <div id="registerFields" style="display: none;">
                <div class="input-group">
                    <input type="text" id="regUsername" placeholder="用户名" required>
                    <div class="error-message" id="regUsernameError"></div>
                </div>
                <div class="input-group">
                    <input type="email" id="email" placeholder="电子邮箱" required>
                    <div class="error-message" id="emailError"></div>
                </div>
                <div class="input-group">
                    <input type="password" id="regPassword" placeholder="密码" required>
                    <div class="error-message" id="regPasswordError"></div>
                </div>
                <div class="input-group">
                    <input type="password" id="confirmPassword" placeholder="确认密码" required>
                    <div class="error-message" id="confirmPasswordError"></div>
                </div>
            </div>

            <div class="form-actions">
                <button type="button" id="denglu">立即登录</button>
                <button type="button" id="zhuce">注册账号</button>
            </div>
            <div class="toggle-text">
                <span id="toggleText">没有账号？立即注册</span>
            </div>
            <div class="success-message" id="successMsg"></div>
        </form>
    </div>

    <script>
        const API_ENDPOINT = {
            login: "https://study.godoai.com/api/user/login",
            register: "https://study.godoai.com/api/user/register"
        };

        let isLoginMode = true;

        // DOM元素缓存
        const elements = {
            authForm: document.getElementById('authForm'),
            loginFields: document.getElementById('loginFields'),
            registerFields: document.getElementById('registerFields'),
            formTitle: document.getElementById('formTitle'),
            toggleText: document.getElementById('toggleText'),
            denglu: document.getElementById('denglu'),
            zhuce: document.getElementById('zhuce'),
            successMsg: document.getElementById('successMsg')
        };

        // 表单验证规则
        const validators = {
            username: value => value.length >= 4,
            password: value => value.length >= 6,
            email: value => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
            confirmPassword: (value, confirmPassword) => value === confirmPassword
        };

        // 切换表单模式
        function toggleAuthMode() {
            isLoginMode = !isLoginMode;
            elements.authForm.classList.toggle('submitting');
            
            if (isLoginMode) {
                elements.formTitle.textContent = '账号登录';
                elements.toggleText.textContent = '没有账号？立即注册';
                elements.loginFields.style.display = 'block';
                elements.registerFields.style.display = 'none';
                elements.denglu.style.display = 'block';
                elements.zhuce.style.display = 'none';
            } else {
                elements.formTitle.textContent = '账号注册';
                elements.toggleText.textContent = '已有账号？立即登录';
                elements.loginFields.style.display = 'none';
                elements.registerFields.style.display = 'block';
                elements.denglu.style.display = 'none';
                elements.zhuce.style.display = 'block';
            }
            
            resetForm();
        }

        // 表单验证
        function validateForm(isRegister = false) {
            const username = document.getElementById(isRegister ? 'regUsername' : 'username').value.trim();
            const password = document.getElementById(isRegister ? 'regPassword' : 'password').value;
            const email = isRegister ? document.getElementById('email').value.trim() : '';
            const confirmPassword = isRegister ? document.getElementById('confirmPassword').value : '';

            let isValid = true;

            // 通用验证
            if (!validators.username(username)) {
                showError(isRegister ? 
                    elements.regUsernameError : elements.usernameError, 
                    '用户名至少需要4个字符');
                isValid = false;
            }

            // 密码验证
            if (!validators.password(password)) {
                showError(isRegister ? 
                    elements.regPasswordError : elements.passwordError, 
                    '密码至少需要6个字符');
                isValid = false;
            }

            // 邮箱验证（仅注册）
            if (isRegister && !validators.email(email)) {
                showError(elements.emailError, '请输入有效的电子邮箱');
                isValid = false;
            }

            // 确认密码验证（仅注册）
            if (isRegister && !validators.confirmPassword(password, confirmPassword)) {
                showError(elements.confirmPasswordError, '两次输入的密码不一致');
                isValid = false;
            }

            return isValid;
        }

        // 错误处理
        function showError(element, message) {
            element.textContent = message;
            element.style.display = 'block';
            elements.authForm.classList.add('shake');
            setTimeout(() => {
                elements.authForm.classList.remove('shake');
                element.style.display = 'none';
            }, 3000);
        }

        // 网络请求
        async function apiRequest(endpoint, data) {
            try {
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 10000);

                const response = await fetch(endpoint, {
                    method: "POST",
                    headers: {
                        "Content-Type": "application/json",
                        "X-Requested-With": "XMLHttpRequest"
                    },
                    body: JSON.stringify(data),
                    signal: controller.signal
                });
                clearTimeout(timeoutId);

                if (!response.ok) throw new Error(`HTTP错误 ${response.status}`);
                return await response.json();
            } catch (error) {
                handleNetworkError(error);
                throw error;
            }
        }

        // 网络错误处理
        function handleNetworkError(error) {
            let message = '网络连接异常';
            if (error.name === 'AbortError') {
                message = '请求超时，请检查网络';
            } else if (error.message.includes('401')) {
                message = '用户名或密码错误';
            }
            showError(elements.usernameError, message);
        }

        // 提交处理
        async function handleSubmit(isRegister) {
            if (!validateForm(isRegister)) return;

            try {
                elements.authForm.classList.add('submitting');
                const data = {
                    username: document.getElementById(isRegister ? 'regUsername' : 'username').value.trim(),
                    password: document.getElementById(isRegister ? 'regPassword' : 'password').value
                };

                if (isRegister) {
                    data.email = document.getElementById('email').value.trim();
                    const result = await apiRequest(API_ENDPOINT.register, data);
                    if (result.code === 1000) {
                        showSuccess('注册成功，请登录');
                        toggleAuthMode();
                    }
                } else {
                    const result = await apiRequest(API_ENDPOINT.login, data);
                    if (result.code === 1000) {
                        showSuccess('登录成功！');
                        setTimeout(() => window.location.href = "./index.html", 1000);
                    }
                }
            } catch (error) {
                console.error(isRegister ? '注册失败' : '登录失败:', error);
            } finally {
                elements.authForm.classList.remove('submitting');
            }
        }

        // 事件绑定
        elements.denglu.addEventListener('click', () => handleSubmit(false));
        elements.zhuce.addEventListener('click', () => handleSubmit(true));
        elements.toggleText.addEventListener('click', toggleAuthMode);

        // 辅助函数
        function resetForm() {
            elements.authForm.querySelectorAll('.error-message').forEach(el => el.style.display = 'none');
            elements.authForm.querySelectorAll('input').forEach(input => input.value = '');
            elements.successMsg.style.display = 'none';
        }

        function showSuccess(message) {
            elements.successMsg.textContent = message;
            elements.successMsg.style.display = 'block';
            setTimeout(() => {
                elements.successMsg.style.display = 'none';
                if(!isLoginMode) toggleAuthMode();
            }, 2000);
        }
    </script>
</body>
</html>